package com.sailfish.springbootdemo.service.db4;

import com.sailfish.springbootdemo.dao.db4.LoginRecordDao;
import com.sailfish.springbootdemo.dao.db4.UserDao;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db4.LoginRecord;
import com.sailfish.springbootdemo.utils.CommonUtils;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class LoginRecordServiceImpl implements LoginRecordService {

    @Autowired
    private LoginRecordDao loginRecordDao;

    @Autowired
    private UserDao userDao;

    @Override
    public Result getAllLoginRecord(String loginResult, Integer page, Integer pageSize) {
        try{
            if (page == null || !CommonUtils.isNumeric(page.toString())) {
                return ResultUtil.error(500, "错误参数page", "Error Param page", null);
            }
            if (pageSize == null || !CommonUtils.isNumeric(pageSize.toString())) {
                return ResultUtil.error(500, "错误参数pageSize", "Error Param pageSize", null);
            }

            int begin = (page - 1) * pageSize;

            List<LoginRecord> list1 = loginRecordDao.getAllLoginRecord(loginResult, begin, pageSize);
            for (LoginRecord loginRecord : list1) {
                loginRecord.setUser(userDao.getUserInfoById(loginRecord.getUserId()));
            }
            List<LoginRecord> list2 = loginRecordDao.getAllLoginRecord(loginResult, null, null);
            return ResultUtil.tableSuccess(page, pageSize, list2.size(), list1);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public void addLoginRecord(LoginRecord loginRecord) {
        loginRecord.setCreateTime(new Date());
        loginRecordDao.addLoginRecord(loginRecord);
    }
}
